<template>
  <div class="student-container">
    <div class="page-header">
      <h2>学生管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加学生
        </el-button>
        <!-- <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button> -->
      </div>
    </div>
    
    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入学号或姓名"
            clearable
          />
        </el-col>
        <el-col :span="8">
          <el-select
            v-model="searchForm.classId"
            placeholder="选择班级"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部班级" value="" />
            <el-option
              v-for="cls in classList"
              :key="cls.id"
              :label="cls.display"
              :value="cls.id"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 学生表格 -->
    <div class="student-table">
      <el-table
        :data="studentList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="sno" label="学号" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="classDisplay" label="班级" min-width="150" />
        <el-table-column prop="createdTime" label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ row.createdTime ? new Date(row.createdTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" min-width="160">
          <template #default="{ row }">
            {{ row.updatedTime ? new Date(row.updatedTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>

            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 学生添加/编辑对话框 -->
    <StudentDialog
      v-model:visible="dialogVisible"
      :student-data="currentStudent"
      :class-list="classList"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Search
} from '@element-plus/icons-vue'
import { getStudentsApi, deleteStudentApi } from '@/api/student/student'
import { getClassOptionsApi } from '@/api/class/class'
import StudentDialog from './components/StudentDialog.vue'

// 响应式数据
const loading = ref(false)
const studentList = ref([])
const classList = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  classId: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentStudent = ref({})

// 数据获取方法
const loadStudents = async () => {
  try {
    loading.value = true

    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 添加搜索条件
    if (searchForm.search) {
      params.search = searchForm.search
    }

    // 添加班级过滤
    if (searchForm.classId) {
      params.class_id = searchForm.classId
    }

    const response = await getStudentsApi(params)

    if (response.code === 200) {
      studentList.value = response.data.data || []
      total.value = response.data.totalCount || 0
      ElMessage.success(`查询到 ${studentList.value.length} 条学生记录`)
    } else {
      ElMessage.error(response.message || '获取学生列表失败')
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  } finally {
    loading.value = false
  }
}

const loadClassOptions = async () => {
  try {
    const response = await getClassOptionsApi()

    if (response.code === 200) {
      classList.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取班级选项失败')
    }
  } catch (error) {
    console.error('获取班级选项失败:', error)
    ElMessage.error('获取班级选项失败')
  }
}

// 方法
const handleSearch = () => {
  currentPage.value = 1  // 重置到第一页
  loadStudents()
}

const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    classId: ''
  })
  currentPage.value = 1
  loadStudents()
}

const handleAdd = () => {
  isEdit.value = false
  currentStudent.value = {}
  dialogVisible.value = true
}

const handleImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

const handleExport = () => {
  ElMessage.info('导出数据功能开发中...')
}

const handleEdit = (row) => {
  isEdit.value = true
  currentStudent.value = { ...row }
  dialogVisible.value = true
}

const handleViewScores = (row) => {
  ElMessage.info(`查看成绩功能开发中... 学生：${row.name}`)
}

const handleDialogSuccess = () => {
  // 对话框操作成功后重新加载数据
  loadStudents()
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${row.name}（${row.sno}）吗？删除后将同时删除该学生的所有成绩记录！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteStudentApi(row.id)

    if (response.code === 200) {
      ElMessage.success(response.message || '删除成功')
      // 重新加载数据
      loadStudents()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除学生失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1  // 重置到第一页
  loadStudents()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadStudents()
}

const initData = async () => {
  await loadClassOptions()
  await loadStudents()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.student-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }
  
  .student-table {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    overflow-x: auto; // 添加水平滚动支持

    // 确保表格占满容器宽度
    :deep(.el-table) {
      width: 100%;
      min-width: 800px; // 设置最小宽度确保内容不会过度压缩
    }

    // 优化表格单元格内容显示
    :deep(.el-table__cell) {
      padding: 12px 8px;
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .student-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;

      .header-actions {
        width: 100%;
        justify-content: flex-start;
        flex-wrap: wrap;
      }
    }

    .search-section {
      padding: 15px;

      .el-col {
        margin-bottom: 15px;
      }
    }

    .student-table {
      padding: 15px;

      // 移动端表格优化
      :deep(.el-table) {
        min-width: 600px; // 移动端减小最小宽度
        font-size: 14px;
      }

      // 操作按钮在移动端垂直排列
      :deep(.el-table__fixed-right) {
        .el-button {
          margin-bottom: 5px;
          display: block;
          width: 100%;
        }
      }
    }
  }
}
</style>
